import axios from 'axios'
import {
  Message,
  Notification,
  Loading
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'

// const loading = Loading.service({
//   target: '.main-container',
//   lock: true,
//   text: 'Loading',
//   spinner: 'el-icon-loading',
//   background: 'rgba(0, 0, 0, 0.7)'
// })

function queryParse(query) {
  let res = []
  for (let k in query) {
    res.push(`${encodeURIComponent(k)}=${encodeURIComponent(query[k])}`)
  }
  return res.join('&')
}
const baseURL = 'http://192.168.121.67:8110'
// const baseURL = 'https://www.golwayhhln.top/backJava'// 智城请求地址
// const baseURL = 'https://www.golwayhhln.top/golwayBackJava'//智安（高德威）请求地址
// const baseURL = '/api'
const service = axios.create({
  baseURL,
  timeout: 15000
})

export const json2fd = json => {
  const fd = new FormData()
  for (let k in json) {
    fd.append(k, json[k])
  }
  return fd
}
service.interceptors.request.use(config => {
  /**
   * auth:tang
   * date:2022.4.22
   * content:请求头更改，token传参方式修改  formdata=>json
   * */
  if (store.getters.token) {
    config.headers['Authorization'] = getToken()
    // config.headers['Content-Type'] = "application/json;charset=UTF-8"
    // config.headers['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8"
  }

  // if (!(config.data instanceof FormData)) {
  //   config.headers['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8"
  //   config.data = queryParse(config.data)
  // }
  return config
}, error => {
  // console.log(error) // for debug
  Promise.reject(error)
})

service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code === 1) {
      return res
    } else if (res.code === 403) {
      // console.log(`res.code---`, res.code);
      Notification({
        title: '警告',
        message: '您的登录凭证已过期，请重新登录,2秒后自动退出系统',
        type: 'warning'
      })
      // setTimeout(() => {
      //   store.dispatch('FedLogOut').then(() => {
      //     location.reload();// 为了重新实例化vue-router对象 避免bug
      //   });
      // }, 2000);
    } else if (res.code === 3) {
      Notification({
        title: '警告',
        message: '用户未登录',
        type: 'warning'
      })
      this.$store.dispatch('FedLogOut').then(() => {
        location.reload() // In order to re-instantiate the vue-router object to avoid bugs
      })

    } else if (res.code === 21) {
      Notification({
        title: '警告',
        message: '您的权限不足',
        type: 'warning'
      })
    } else {
      Message({
        message: res.msg,
        type: 'error',
        duration: 8 * 1000
      });
      return Promise.reject(res)
      // return res
    }
  },
  error => {
    //for debug
    Message({
      message: error.message || error.msg,
      type: 'error',
      duration: 8 * 1000
    })
    return Promise.reject(error)
  })

export default service
